/**
 * Created by xuxin on 16/4/19.
 */
import Vue from 'vue'
import Conf from 'config'

const localUser = 'userInfo'

const defaultAvatar = require('../assets/img/account/nologin.png')
//hm:默认User配置
const dafaultUser = {
  avatar: defaultAvatar
}

// fzc: accountBalance/top_xhh_amount_view 已经没有应用场景,全局搜索过
// 之前有用主要用于一个单独的充值/提现页，已经已经删除
// 删除
let userService = {
  user: dafaultUser,
  setUser (obj) {
    // 只要是更新用户信息，就一定是登陆状态
    Conf.isLogin = true
    Object.assign(this.user, {
      avatar: defaultAvatar
    }, obj)
    this.user.is_passwd_recharge = parseInt(this.user.is_passwd_recharge)
    this.user.avatar = this.user['ava'] && this.user['ava']['url_s300'] ? this.user['ava']['url_s300'] : this.user.avatar
    //Vue.set(this.user)
    //localData.set(localUser, this.user)
  },
  getUser (vm, cb) {
    this.getUserFromLocal()
    if (this.isInCache()) {
      cb && cb.call(vm, this.user)
    } else {
      //防止localStorage被清空
      //先判断是否登录,若登录则请求用户信息,否则不处理
      userService.getUserFromRemote(vm, cb)
    }
    return this.user
  },
  getUserFromLocal () {
    if (!this.isInCache() && localData.get(localUser)) {
      this.user = localData.get(localUser)
    }
    return this.user
  },
  getUserFromRemote: function (vm, cb) {
    // Api.userInfo.call(this, {
    //   resolve: function (json) {
    //     if (json.boolen === 1) {
    //       //if (json.data !== '请先登录吧') {
    //       userService.setUser(json.data)
    //       // if (userService.user.accountBalance === 0) {
    //       //   userService.getAccountBalance()
    //       // }
    //       cb && cb.call(vm, userService.user)
    //       //}
    //     }
    //   }
    // })
  },
  init: function (isGetFromRemote) {
    if (isGetFromRemote) {
      userService.getUser()
    } else {
      userService.getUserFromLocal()
    }
  },
  isInCache () {
    return this.user.uid
  },
  getAva () {
    return this.user.avatar
  },
  setAva (val) {
    this.user.avatar = val
    //localData.set(localUser, this.user)
    return this.user.avatar
  },
  getAttr (attr) {
    return this.user[attr]
  },
  setAttr (attr, val) {
    if (attr) {
      //Vue.set(this.user, attr, val)
      //localData.set(localUser, this.user)
    }
  },
  clear () {
    this.user = dafaultUser
    //localData.remove(localUser)
  }
}

export default userService
